//
//  LSListenNewQuesView.m
//  听说弱点强化训练
//
//  Created by 盛超 on 2018/10/22.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "LSListenNewQuesView.h"
#import "LSListenCell.h"
#import "LSIndexProgressView.h"
#import "LSListenTestView.h"
#import "LSGetZSDManager.h"
#import "DicMainView.h"
#import "LSSaveZSDManager.h"
#import <WebKit/WebKit.h>
#import "KZSoundTool.h"
#import "BKListenAnswerView.h"

@interface LSListenNewQuesView ()<UITableViewDelegate,UITableViewDataSource,UIWebViewDelegate,WKNavigationDelegate,LSListenTestViewDelegate,TYAttributedLabelDelegate,DicMainViewDelegate>

@property (nonatomic,strong) UITableView *tabelView;
@property (nonatomic,strong) NSTimer *timer;

/**
 section头部视图数组
 */
@property (nonatomic,strong) NSMutableArray *sectionViewArr;

/**
 主题干视图
 */
@property (nonatomic,strong) UIView *tableHeaderView;

/**
 流程交互界面
 */
@property (nonatomic,strong) LSListenTestView *testView;

/*
 *需要刷新的indexPath
 */
@property (nonatomic,strong) NSMutableArray *indexPathArr;

/**
 知识点
 */
@property (nonatomic,strong) NSMutableArray *mutlCodeArr;
@property (nonatomic,strong) NSMutableArray *mutlNameArr;

/**
 字典
 */
@property (nonatomic,strong) DicMainView *dictView;


@end

@implementation LSListenNewQuesView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setUI];
    }
    return self;
}

- (instancetype)init {
    if (self = [super init]) {
        [self setUI];
    }
    
    return self;
}

- (void)setUI {
    
    _indexPathArr = [NSMutableArray array];
    self.backgroundColor = [UIColor whiteColor];
    [self addSubview:self.tabelView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TimeReleaseAction) name:@"TimeRelease" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TimePauseAction) name:@"TimePause" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TimeResumeAction) name:@"TimeResume" object:nil];
    
}


- (UITableView *)tabelView {
    if (!_tabelView) {
        _tabelView = [[UITableView alloc] initWithFrame:CGRectMake(0,0,kWidth,kHeight-kNavgationBar-48) style:UITableViewStyleGrouped];
        _tabelView.backgroundColor = [UIColor whiteColor];
        _tabelView.delegate = self;
        _tabelView.dataSource = self;
        _tabelView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tabelView registerClass:[LSListenCell class] forCellReuseIdentifier:@"LSListenCell"];
        [_tabelView registerClass:[LSListenHeader class] forHeaderFooterViewReuseIdentifier:@"LSListenHeader"];
        _tabelView.tableHeaderView = [UIView new];
        _tabelView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 150)];
    }
    return _tabelView;
}

- (void)setModel:(LSModelQues *)model {
    _model = model;
    if (_answerDict==nil) {
        _answerDict = [NSMutableDictionary dictionary];
    }
    _sectionViewArr = [NSMutableArray arrayWithCapacity:_model.ChildList.count];
    for (NSInteger i = 0; i<_model.ChildList.count; i++) {
        [_sectionViewArr addObject:[UIView new]];
        LSChild *child = _model.ChildList[i];
        NSString *string = [self.answerDict objectForKey:[NSString stringWithFormat:@"%ld",i+1]];
        child.ChildStuAnswer = string?string:@"";
    }
    
    [self.tabelView reloadData];
    [self setupTableViewHeader];
    
//    [self startSource];
    if (_answerState==2) {
        _tabelView.allowsSelection = NO;
        [self setupTableViewFooter];
    }
    
}

//添加主题干
- (void)setupTableViewHeader {
    UIView *tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth,10)];
    if ([self.model.QuesBody isEqualToString:@""] || self.model.QuesBody==nil) {
        
        self.tabelView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 2)];;
        
        return;
    }
    
    //大题题干
    self.tableHeaderView = tableHeaderView;
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,kWidth,10)];
    [tableHeaderView addSubview:webView];
    webView.userInteractionEnabled = NO;
    webView.delegate = self;
    [webView loadHTMLString:[self.model.QuesBody webViewHtmlStringWithFont:17.0f] baseURL:nil];
//    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0,0,kWidth,10)];
//    [tableHeaderView addSubview:webView];
//    webView.navigationDelegate = self;
//    [webView loadHTMLString:[self.model.QuesBody webViewHtmlStringWithFont:17.0f] baseURL:nil];
}

//- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
//    [webView evaluateJavaScript:@"document.body.scrollHeight" completionHandler:^(id _Nullable finishHeight, NSError * _Nullable error) {
//        dispatch_async(dispatch_get_main_queue(), ^{
//            CGFloat height = [finishHeight floatValue];
//            [webView sizeToFit];
//            webView.scrollView.contentSize = CGSizeMake(kWidth,0);
//            webView.scrollView.showsVerticalScrollIndicator = NO;
//            webView.scrollView.showsHorizontalScrollIndicator = NO;
//            webView.height = height;
//            self.tableHeaderView.height = height;
//            self.tabelView.tableHeaderView = self.tableHeaderView;
//        });
//
//    }];
//
//}

//添加听力原文
- (void)setupTableViewFooter {
    
    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 150)];
    
    UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(12, 0, kWidth-24, 1)];
    line.backgroundColor = [UIColor colorWithHex:0xe1e1e1];
    [footer addSubview:line];
    
    TYAttributedLabel *quesBody = [[TYAttributedLabel alloc] initWithFrame:CGRectMake(12,28, kWidth-24, 10)];
    [footer addSubview:quesBody];
    LSAVdio *avdio = self.model.AudioList.firstObject;
    NSString *string = [NSString stringWithFormat:@"<font color=\"#525252\">听力原文:</font><br>%@",avdio.Article];
    quesBody.attributedText = [string dr_changeCharSpace:1.5 LineSpace:5 Font:15];// [string dr_HtmlStringWithFontSize:15];
    quesBody.numberOfLines = 0;
    quesBody.linesSpacing = 5;
    quesBody.characterSpacing = 1.5;
    quesBody.lineBreakMode = NSLineBreakByWordWrapping;
    [quesBody sizeToFit];
    if (self.answerState==1) {
        quesBody.delegate = self;
        [MBProgressHUD showClearStyleToView:quesBody];
        if (_mutlCodeArr) {
            [self setupLabel:quesBody HightlightlyString:quesBody.attributedText.string Words:_mutlNameArr Codes:_mutlCodeArr];
            [MBProgressHUD hideHUDForView:quesBody animated:YES];
        } else {
            double delayInSeconds = 5.0;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                //执行事件
                 [self setupLabel:quesBody HightlightlyString:quesBody.attributedText.string Words:_mutlNameArr Codes:_mutlCodeArr];
                [MBProgressHUD hideHUDForView:quesBody animated:YES];
            });
        }
    }
    
    footer.height = quesBody.height+28+200;
    
    self.tabelView.tableFooterView = footer;
}

#pragma mark - 提交保存/重新作答
- (void)judegeResult {
    
    //错误抖动动画
    CABasicAnimation* shake = [CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
    shake.fromValue = [NSNumber numberWithFloat:-5];
    shake.toValue = [NSNumber numberWithFloat:5];
    shake.duration = 0.2;//执行时间
    shake.autoreverses = YES; //是否重复
    shake.repeatCount = 5;//次数
  
    //显示作答正确/错误的选项
    self.answerState = 1;
    self.tabelView.allowsSelection=NO;
    
    [_indexPathArr removeAllObjects];
    for (NSInteger i = 0; i<self.model.ChildList.count; i++) {
        LSChild *child = _model.ChildList[i];
        NSInteger trueRow = [child.ChildAnswer characterAtIndex:0];
        //有作答
        if (![child.ChildStuAnswer isEqualToString:@""] && child.ChildStuAnswer!=nil ) {
            NSInteger selectRow =[child.ChildStuAnswer characterAtIndex:0];
            NSIndexPath *indexPath2 = [NSIndexPath indexPathForRow:selectRow-65 inSection:i];
            [_indexPathArr addObject:indexPath2];
            if(selectRow!=trueRow) {
                LSListenCell *cell = [self.tabelView cellForRowAtIndexPath:indexPath2];
                [cell.layer addAnimation:shake forKey:@"shake"];
            }
        }
    }
    [self.tabelView reloadRowsAtIndexPaths:_indexPathArr withRowAnimation:UITableViewRowAnimationFade];
    
    //分析作答结果
    NSInteger count = 0;
    for (NSInteger i = 0; i<self.model.ChildList.count; i++) {
        LSChild *child = self.model.ChildList[i];
        NSString *stuAnswer = [self.answerDict objectForKey:[NSString stringWithFormat:@"%ld",i+1]];
        if ([stuAnswer isEqualToString:child.ChildAnswer]) {
            count ++;
        }
    }
    //返回代理(提交试题)
    CGFloat correctRate = (count*1.00)/(self.model.TotalItemCount*1.00);
    if (self.isReAnswer==NO) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(FinishAnswerQues:CorrectRate:IsSave:)]) {
            [self.delegate FinishAnswerQues:self.answerDict CorrectRate:correctRate IsSave:NO];
        }
    }
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(nextAction:) userInfo:@(count) repeats:NO];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];

}

//提交后接下来界面显示
- (void)nextAction:(NSTimer*)timer {
    
    NSInteger count = ((NSNumber*)timer.userInfo).integerValue;
    [_timer invalidate];
    _timer = nil;
    
    if (count==self.model.TotalItemCount) { //正确
       // [KZSoundTool playSound:KZSoundType_correct];
        LSSoundPlayer *player = [[LSSoundPlayer alloc] initWithSound:KZSoundType_correct];
        self.soundPlayer = player;
        
        if(!self.isReAnswer) { //第一次作答就正确了
            //直接进去下一题
            double delayInSeconds = 0.5;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                //执行事件
                if (self.delegate && [self.delegate respondsToSelector:@selector(willEnterNextQues)]) {
                    [self.delegate willEnterNextQues];
                }
            });
        
        } else {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //显示听力原文
                [self setupTableViewFooter];
                //滚动到底部
                LSChild *child = self.model.ChildList.lastObject;
                [self.tabelView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:child.ChildOptionList.count-1 inSection:self.model.ChildList.count-1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
                //只显示下一题按钮
                [self.testView showNext];
                
                if (self.delegate && [self.delegate respondsToSelector:@selector(retrunShowComplteView)]) {
                    //错题时显示弹窗
                    
                    [self.delegate retrunShowComplteView];
                    
                }
            });
            
        }
        
        
    } else { //错误
        //[KZSoundTool playSound:KZSoundType_wrong];
        LSSoundPlayer *player = [[LSSoundPlayer alloc] initWithSound:KZSoundType_wrong];
        self.soundPlayer = player;
        
        if(!self.isReAnswer) { //第一次作答就错误了
            
            if (self.mutlCodeArr.count==0) {
                [self getZSDHightly:_model.AudioList.firstObject.Article];
            }
            
            self.isReAnswer = YES;
            //直接重新作答
            [self.answerDict removeAllObjects];
            for (NSInteger i = 0; i<_model.ChildList.count; i++) {
                
                [_sectionViewArr addObject:[UIView new]];
                LSChild *child = _model.ChildList[i];
                NSString *string = [self.answerDict objectForKey:[NSString stringWithFormat:@"%ld",i+1]];
                child.ChildStuAnswer = string?string:@"";
            }
            self.answerState = 0;
            self.tabelView.allowsSelection=YES;
            [self.tabelView reloadRowsAtIndexPaths:_indexPathArr withRowAnimation:UITableViewRowAnimationFade];
            [self.tabelView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            
            self.tabelView.userInteractionEnabled = NO;
            _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeAction:) userInfo:nil repeats:NO];
            
        } else {
             dispatch_async(dispatch_get_main_queue(), ^{
                //显示听力原文
                [self setupTableViewFooter];
                 //滚动到底部
                LSChild *child = self.model.ChildList.lastObject;
                [self.tabelView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:child.ChildOptionList.count-1 inSection:self.model.ChildList.count-1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
                //显示重新作答和下一题按钮
                [self.testView showNextAndReAnswer];
                 
                 if (self.delegate && [self.delegate respondsToSelector:@selector(retrunShowComplteView)]) {
                     //错题时显示弹窗
                     
                     [self.delegate retrunShowComplteView];
                     
                 }
            });
        }
        
    }

}

- (void)timeAction:(id)sender {
    
    self.tabelView.userInteractionEnabled = YES;
    
    [_timer invalidate];
    _timer = nil;
    
    [self.testView startSecond];
}

#pragma mark - 获取高亮知识点
- (void)getZSDHightly:(NSString*)text {
    LSGetZSDManager *manager = [[LSGetZSDManager alloc] init];
    manager.requestParam = @{@"Text":text,
                             @"stageNo":KGetUserDefaults(@"TestLayer")
                             };
    WeakObj(self);
    [manager requestWithCompltionSuccess:^(NSArray *zsdArr) {
        
        selfWeak.mutlCodeArr = [NSMutableArray array];
        selfWeak.mutlNameArr = [NSMutableArray array];
        for (LSModelZSD *zsd in zsdArr) {
            [selfWeak.mutlCodeArr addObject:zsd.ZSDCode];
            [selfWeak.mutlNameArr addObject:zsd.ZSDNameInText];
        }
        
    } failuer:^(NSString *error) {
        
    }];
}

//**加载高亮**//
- (void)setupLabel:(TYAttributedLabel*)textLabel HightlightlyString:(NSString*)text Words:(NSArray*)words Codes:(NSArray*)codes{
    NSString *string = text;
    
    NSMutableArray *removeHadArr = [NSMutableArray array];
    [string enumerateSubstringsInRange:NSMakeRange(0, string.length-1) options:NSStringEnumerationByWords usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) {
        
        if([words containsObject:substring] && ![removeHadArr containsObject:substring]) {
            
            [removeHadArr addObject:substring];
            
            NSInteger index = [words indexOfObject:substring];
            NSString *linkData = [NSString stringWithFormat:@"%@|%@",codes[index],substring];
            [textLabel addLinkWithLinkData:linkData linkColor:[UIColor orangeColor] underLineStyle:kCTUnderlineStyleSingle range:substringRange];
        }
    }];
    
}

#pragma mark - 播放器，倒计时等交互模块
- (void)startSource {
    UIView *backView = [[UIView alloc] init];
  //  backView.backgroundColor = [UIColor whiteColor];
    [self addSubview:backView];
    [backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self);
        make.height.mas_equalTo(W(160));
    }];
    
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = CGRectMake(0, 0, kWidth, W(160));
    gradientLayer.startPoint = CGPointMake(0, 0);
    gradientLayer.endPoint = CGPointMake(0, 1);
    gradientLayer.locations = @[@0,@0.3,@1];
    gradientLayer.colors = @[
                              (__bridge id)kzRGBA(255, 255, 255,0.2).CGColor,
                              (__bridge id)kzRGBA(255, 255, 255, 1).CGColor,
                              (__bridge id)kzRGBA(255, 255, 255, 1).CGColor,
                              ];
    [backView.layer insertSublayer:gradientLayer atIndex:0];
    
    LSListenTestView *testView = [[LSListenTestView alloc] init];
    self.testView = testView;
    [backView addSubview:testView];
    testView.delegate = self;
    testView.from = _from;
    testView.speedLayer = _speedLayer;
    testView.model = _model;
    [testView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(W(120));
        make.centerX.equalTo(backView);
        make.bottom.equalTo(backView.mas_bottom).offset(W(-40));
    }];
    
    if (_answerState==2) {
        [testView showPlayerVoice];
    } else {
        [testView start];
    }
}

- (void)pauseSource {
    
}

- (void)freeSource {
    
}

- (void)reStartSource:(NSInteger)speedLayer {
    [self.testView reStartSpeedLayer:speedLayer];
}

#pragma mark - LSTYAttributedLabelDelegate
- (void)attributedLabel:(TYAttributedLabel *)attributedLabel textStorageClicked:(id<TYTextStorageProtocol>)textStorage atPoint:(CGPoint)point {
    if ([textStorage isKindOfClass:[TYLinkTextStorage class]]) {
        NSString *linkStr = ((TYLinkTextStorage*)textStorage).linkData;
        NSLog(@"%@",linkStr);
        
        _dictView = [[DicMainView alloc] initWithTestType:DictTestType_Word isShowRecord:YES];
        _dictView.delegate = self;
        _dictView.dictUrl = [NSString stringWithFormat:@"%@api/ZXYYTS/W_ZXYYTS_GetCoursewareByCode",KGetUserDefaults(@"SystemIP")];
        _dictView.dictParam = @{
                                @"knowledge":[linkStr componentsSeparatedByString:@"|"].firstObject,
                                @"levelCode":KGetUserDefaults(@"TestLayer"),
                                @"stageNo":KGetUserDefaults(@"TestLayer"),
                                @"schoolId":DR_UserInfo.SchoolID,
                                @"stuId":DR_UserInfo.UserID,
                                };
        
        [_dictView popAnimated:YES];
        
        LSSaveZSDManager *manager = [[LSSaveZSDManager alloc] init];
        
        NSDictionary *dict = @{@"StageNo":KGetUserDefaults(@"TestLayer"),
                               @"SchoolID":KGetUserDefaults(@"SchoolID"),
                               @"StuID":DR_UserInfo.UserID,
                               @"VocabularyID":[linkStr componentsSeparatedByString:@"|"].firstObject,
                               @"Vocabulary":[linkStr componentsSeparatedByString:@"|"].lastObject,
                               @"IsPassed":@0,
                               @"ReviewPassedCount":@0,
                               @"NeedReviewCount":@3,
                               @"CreateTime":[NSDate date] ,
                               @"UpdateTime":[NSDate date]
                               };
        manager.requestParam = @{
                                 @"stageNo":KGetUserDefaults(@"TestLayer"),
                                 @"schoolId":DR_UserInfo.SchoolID,
                                 @"stuId":DR_UserInfo.UserID,
                                 @"ModelUnfamiliarVocabularyList":@[dict]
                                 };
        
        [manager requestSaveWithCompltionSuccess:^(NSString *string) {
            NSLog(@"保存知识点");
        } failuer:^(NSString *error) {
            
        }];
        
    }
    
    
}

#pragma mark - WebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString *js =[NSString stringWithFormat:@"function imgAutoFit() { \
                       var imgs = document.getElementsByTagName('img'); \
                       for (var i = 0; i < imgs.length; ++i) {\
                       var img = imgs[i];   \
                       img.style.maxWidth = %f;   \
                       } \
                       }",kWidth-20];
        js = [NSString stringWithFormat:js, [UIScreen mainScreen].bounds.size.width ];
        [webView stringByEvaluatingJavaScriptFromString:js];
        [webView stringByEvaluatingJavaScriptFromString:@"imgAutoFit()"];
        // 获取webView的高度
        CGFloat webViewHeight = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
        CGFloat webViewWidth = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollWidth"] floatValue];
        webView.scrollView.contentSize = CGSizeMake(webViewWidth,0);
        webView.scrollView.showsVerticalScrollIndicator = NO;
        webView.scrollView.showsHorizontalScrollIndicator = NO;
        webView.height = webViewHeight+10;
        [webView sizeToFit];
        self.tableHeaderView.height = webView.height;
        self.tabelView.tableHeaderView = self.tableHeaderView;
    });
}

#pragma mark - UITabelViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    LSChild *child = self.model.ChildList[indexPath.section];
    NSString *stuAnswer = [NSString stringWithFormat:@"%c",(int)(indexPath.row+65)];
    child.ChildStuAnswer = stuAnswer;//存储学生作答到model中
    for (NSInteger i = 0; i<child.ChildOptionList.count; i++) {
        NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:i inSection:indexPath.section];
        LSListenCell *cell = [tableView cellForRowAtIndexPath:newIndexPath];
        if (i==indexPath.row) {
            cell.optionStyle = LSSelectOptionBlue;//选中
        } else {
            cell.optionStyle = LSSelectOptionWhite;
        }
    }
    
    [self.answerDict setObject:stuAnswer forKey:[NSString stringWithFormat:@"%ld",indexPath.section+1]];
    
    if (self.answerDict.count==self.model.ChildList.count) {
        //交互界面结束操作
        [self.testView stop];
        //提交判断结果并进行下一步操作
        [self judegeResult];
        
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    LSChild *child = self.model.ChildList[indexPath.section];
    LSOption *optionModel = child.ChildOptionList[indexPath.row];

    if (optionModel.cellHeight+17<=50) {
        return 50;
    }

    return optionModel.cellHeight+17;
}

//- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
//
//    return 100;
//
//}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (self.model) {
        LSChild *child = self.model.ChildList[section];
        
        NSString *ask = [NSString stringWithFormat:@"%ld.%@",section+1,child.ChildAsk?child.ChildAsk:@""];
        
        NSAttributedString *attributedText = [ask dr_changeCharSpace:1.5 LineSpace:5 Font:17]; //[ask dr_HtmlStringWithFontSize:17.0f];
        
        CGSize size = [attributedText boundingRectWithSize:CGSizeMake(kWidth-20, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
        
        return size.height+20;
    }
    
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    if (_answerState==2) {
        return 130;
    }
    
    return 20;
}


//section头部视图
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    LSListenHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"LSListenHeader"];
    LSChild *child = self.model.ChildList[section];
    header.section = section;
    header.child = child;
    
    return header;
}

- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    if (_answerState==2) {
        
        BKListenAnswerView *footerView = [[BKListenAnswerView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 128)];
        LSChild *child = self.model.ChildList[section];
        footerView.myAnswer = child.ChildStuAnswer;
        footerView.tureAnswer = child.ChildAnswer;
        
        return footerView;
    }
    
    return [UIView new];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.model.ChildList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    LSChild *child = self.model.ChildList[section];
    
    return child.ChildOptionList.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LSListenCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LSListenCell"];
    LSChild *child = self.model.ChildList[indexPath.section];
    cell.model = child.ChildOptionList[indexPath.row];
    cell.optionStyle = LSSelectOptionWhite;
    //如果存在作答，显示选项的选中内容
    if (self.answerState==0) {
        if (![child.ChildStuAnswer isEqualToString:@""] && child.ChildStuAnswer!=nil ) {
            NSInteger selectRow =[child.ChildStuAnswer characterAtIndex:0];
            if (indexPath.row==selectRow-65) {
                cell.optionStyle = LSSelectOptionBlue;
            }
        }
    } else {
        //cell.userInteractionEnabled = NO;
        if (![child.ChildStuAnswer isEqualToString:@""] && child.ChildStuAnswer!=nil ) {
            
            NSInteger trueRow = [child.ChildAnswer characterAtIndex:0];
            NSInteger selectRow =[child.ChildStuAnswer characterAtIndex:0];
            if (trueRow==selectRow && selectRow-65==indexPath.row) {
                
                cell.optionStyle = LSSelectOptionGreen;
                
            } else if(trueRow!=selectRow && selectRow-65==indexPath.row){
                
                cell.optionStyle = LSSelectOptionRed;
                
            } else {
                
                cell.optionStyle = LSSelectOptionWhite;
                
            }
            
        }
    }
    
    
    return cell;
}

#pragma mark - LSListenTestViewDelegate
- (void)LSListenTestViewEnd {
    [self judegeResult];
}

- (void)LSListenReAnswer {
    self.isReAnswer = YES;
    //直接重新作答
    [self.answerDict removeAllObjects];
    for (NSInteger i = 0; i<_model.ChildList.count; i++) {
        
        [_sectionViewArr addObject:[UIView new]];
        LSChild *child = _model.ChildList[i];
        NSString *string = [self.answerDict objectForKey:[NSString stringWithFormat:@"%ld",i+1]];
        child.ChildStuAnswer = string?string:@"";
    }
    self.answerState = 0;
    self.tabelView.allowsSelection=YES;
    [self.tabelView reloadRowsAtIndexPaths:_indexPathArr withRowAnimation:UITableViewRowAnimationFade];
    self.tabelView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 150)];
    [self.tabelView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    
    [self.testView startSecond];
}

- (void)LSListenNext {
    //切下一题时，进行释放
    self.testView.alpha = 0;
    [self TimeReleaseAction];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(willEnterNextQues)]) {
        [self.delegate willEnterNextQues];
    }
}

#pragma mark - DicMainViewDelegate
- (void)colseDicMainView:(UIView *)dictView {
    [dictView removeFromSuperview];
    dictView = nil;
}

#pragma mark - Notification
-(void)TimeReleaseAction {
    [self.testView stop];
}

-(void)TimePauseAction {
    if (_timer) {
        [_timer setFireDate:[NSDate distantFuture]];
    }
    [self.testView pause];
}

-(void)TimeResumeAction {
    if (_timer) {
        [_timer setFireDate:[NSDate distantPast]];
    }
    [self.testView resume];
}


@end

@implementation LSListenHeader {
    TYAttributedLabel *_textLabel;
}

- (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithReuseIdentifier:reuseIdentifier]) {
        self.backgroundColor = [UIColor whiteColor];
        
        _textLabel = [[TYAttributedLabel alloc] initWithFrame:CGRectMake(10, 0, kWidth-20, 10)];
        _textLabel.numberOfLines = 0;
        _textLabel.lineBreakMode = NSLineBreakByWordWrapping;
//        _textLabel.characterSpacing = 2;
//        _textLabel.linesSpacing = 5;
        [self addSubview:_textLabel];

    }
    return self;
}

- (void)setChild:(LSChild *)child {
    _child = child;
    NSString *ask = [NSString stringWithFormat:@"%ld.%@",_section+1,_child.ChildAsk?_child.ChildAsk:@""];
    //_textLabel.attributedText = [ask dr_HtmlStringWithFontSize:17.0f];
    _textLabel.attributedText = [ask dr_changeCharSpace:1.5 LineSpace:5 Font:17];
    
    if (_child.sectionHeight) {
        
        _textLabel.height = _child.sectionHeight;
        
    } else {
        [_textLabel sizeToFit];
        
        _child.sectionHeight = _textLabel.height;
    }
}

@end
